import { PrismaClient } from '@prisma/client';
import { logger } from './logger';

// 创建Prisma客户端实例
const prisma = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
    {
      emit: 'event',
      level: 'error',
    },
    {
      emit: 'event',
      level: 'info',
    },
    {
      emit: 'event',
      level: 'warn',
    },
  ],
});

// 监听Prisma日志事件
prisma.$on('query', (e: any) => {
  logger.debug(`Query: ${e.query}`);
  logger.debug(`Params: ${e.params}`);
  logger.debug(`Duration: ${e.duration}ms`);
});

prisma.$on('error', (e: any) => {
  logger.error('Prisma error:', e);
});

prisma.$on('info', (e: any) => {
  logger.info('Prisma info:', e.message);
});

prisma.$on('warn', (e: any) => {
  logger.warn('Prisma warning:', e.message);
});

// 数据库连接函数
export const connectDatabase = async (): Promise<void> => {
  try {
    await prisma.$connect();
    logger.info('Database connected successfully');
  } catch (error) {
    logger.error('Failed to connect to database:', error);
    throw error;
  }
};

// 数据库断开连接函数
export const disconnectDatabase = async (): Promise<void> => {
  try {
    await prisma.$disconnect();
    logger.info('Database disconnected successfully');
  } catch (error) {
    logger.error('Failed to disconnect from database:', error);
    throw error;
  }
};

// 导出Prisma客户端
export { prisma };